<template>
  <div class="test-sip">
    <!-- <el-switch v-model="logFlag" active-text="打开日志" inactive-text="关闭日志"> </el-switch> -->
    <div class="step">
      <h2>步骤 1：输入自己的分机号（1001-1019）</h2>
      <div class="step-box">
        <el-input
          v-model="state.sipName"
          placeholder="请输入自己的分机号（1001-1010）"
          class="input-box"
        ></el-input>
        <el-button
          type="primary"
          @click="registerUser"
          class="step-button"
          :disabled="!state.sipName"
        >
          注册
        </el-button>
        <el-button
          type="primary"
          @click="unregisterUser"
          class="step-button"
          :disabled="!state.isRegisted"
        >
          取消注册
        </el-button>
      </div>
    </div>

    <div class="step">
      <h2>步骤 2：输入要呼叫的分机号（1001-1019）</h2>
      <div class="step-box">
        <el-input
          v-model="state.targetNumber"
          placeholder="请输入要呼叫的分机号（1001-1010）"
          class="input-box"
          :disabled="!state.isRegisted"
        ></el-input>
      </div>
      <div class="step-box">
        <el-button
          type="primary"
          @click="startCall(false)"
          class="step-button"
          :disabled="!state.targetNumber || !state.isRegisted"
        >
          拨打语音电话
        </el-button>
        <el-button
          type="primary"
          @click="startCall(true)"
          class="step-button"
          :disabled="!state.targetNumber || !state.isRegisted"
        >
          拨打视频电话
        </el-button>
        <el-button @click="switchToVideo" :disabled="!state.isCalling"> 切换视频 </el-button>
        <el-button @click="switchToAudio" :disabled="!state.isCalling"> 切换语音 </el-button>
      </div>
    </div>

    <div class="step">
      <h2>其他操作</h2>
      <div class="step-box">
        <el-button
          type="primary"
          @click="hangUpCall"
          class="step-button"
          :disabled="!state.isCalling && !state.isRinging"
        >
          挂断
        </el-button>
        <el-button
          v-if="!state.isHold"
          type="primary"
          class="step-button"
          @click="hold"
          :disabled="!state.isCalling"
        >
          呼叫保持
        </el-button>
        <el-button
          v-else
          type="primary"
          class="step-button"
          @click="unhold"
          :disabled="!state.isCalling"
        >
          取消保持
        </el-button>
        <el-button
          v-if="!state.isMute"
          type="primary"
          class="step-button"
          @click="handleMute"
          :disabled="!state.isCalling"
        >
          静音
        </el-button>
        <el-button
          v-else
          type="primary"
          class="step-button"
          @click="handleUnMute"
          :disabled="!state.isCalling"
        >
          取消静音
        </el-button>
        <el-button
          v-if="!state.isShareDesk"
          type="primary"
          class="step-button"
          @click="desktopSharing"
          :disabled="!state.isCalling"
        >
          共享桌面
        </el-button>
        <el-button
          v-else
          type="primary"
          class="step-button"
          @click="endDesktopSharing"
          :disabled="!state.isCalling"
        >
          结束共享
        </el-button>
        <el-button
          v-if="!localStream"
          class="step-button"
          @click="captureLocalMedia"
          :disabled="state.isCalling"
        >
          测试本地设备
        </el-button>
        <el-button v-else class="step-button" @click="stopLocalMedia" :disabled="state.isCalling">
          停止测试本地设备
        </el-button>
      </div>
    </div>

    <div class="step">
      <h2>视频</h2>
      <div class="step-box">
        <div>
          <div>本地</div>
          <video ref="localVideo" playsinline autoplay></video>
        </div>
        <div>
          <div>远程</div>
          <video ref="remoteVideo" playsinline autoplay></video>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, shallowRef } from 'vue';
import JsSIPSDK from '../jssip-sdk';
import { ElMessageBox } from 'element-plus';

// const JsSIPSDK = window.JsSIPSDK;

const state = reactive({
  sipName: 'h5_100',
  targetNumber: 'h5_100',
  isRegisted: false,
  isRinging: false,
  isCalling: false,
  isMute: false,
  isShareDesk: false,
});
const sip = shallowRef();
const localVideo = ref();
const remoteVideo = ref();
const localStream = shallowRef();

const defaultConfig = {
  wssIp: 'wss:test.yuanwangcao.asia:7444',
  serverIp: '135.31.67.193:5080',
  sipIp: '135.31.67.193',
  password: 'rhtx2024',
};

const startCall = isVideo => {
  sip.value.call(state.targetNumber, isVideo ? 'video' : 'audio');
};

const switchToVideo = () => {
  sip.value.switchToVideo();
};
const switchToAudio = () => {
  sip.value.switchToVideo();
};

const hangUpCall = () => {
  sip.value.hangup();
};

const handleMute = () => {
  sip.value.mute();
  state.isMute = true;
};
const handleUnMute = () => {
  sip.value.unmute();
  state.isMute = false;
};

const hold = () => {
  sip.value.hold();
  state.isHold = true;
};
const unhold = () => {
  sip.value.unhold();
  state.isHold = false;
};

const registerUser = () => {
  sip.value.init({
    ...defaultConfig,
    sipName: state.sipName,
  });
};
const unregisterUser = () => {
  sip.value.unregister();
};

function captureLocalMedia() {
  console.log('获取到本地音频/视频');
  navigator.mediaDevices
    .getUserMedia({
      audio: true,
      video: true,
    })
    .then(stream => {
      console.log('获取到本地媒体流', stream);
      localStream.value = stream;

      if (stream.getVideoTracks().length > 0) {
        if ('srcObject' in localVideo.value) {
          localVideo.value.srcObject = stream;
        } else {
          localVideo.value.src = window.URL.createObjectURL(stream);
        }
        // localVideo.value.play();
      }
      if (stream.getAudioTracks().length > 0) {
        if ('srcObject' in sip.value.localAudio) {
          sip.value.localAudio.srcObject = stream;
        } else {
          sip.value.localAudio.src = window.URL.createObjectURL(stream);
        }
        sip.value.localAudio.play();
      }
    });
}

function stopLocalMedia() {
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => track.stop());
    localStream.value = null;
    // 清空音频和视频的 srcObject
    clearMedia(sip.value.localAudio);
    clearMedia(localVideo.value);
  }
}

function clearMedia(media) {
  let mediaSrcObject = media.srcObject;
  if (mediaSrcObject) {
    let tracks = mediaSrcObject.getTracks();
    console.log(tracks);
    for (let i = 0; i < tracks.length; i++) {
      tracks[i].stop();
    }
  }
  media.srcObject = null;
}

async function desktopSharing() {
  await sip.value.desktopSharing();
  state.isShareDesk = true;
}
async function endDesktopSharing() {
  await sip.value.endDesktopSharing();
  state.isShareDesk = false;
}

onMounted(() => {
  sip.value = new JsSIPSDK();
  sip.value.setVideoDom({
    localVideo: localVideo.value,
    remoteVideo: remoteVideo.value,
  });
  sip.value.on('registered', e => {
    console.log('registered', e);
    state.isRegisted = true;
  });
  sip.value.on('unregistered', e => {
    console.log('unregistered', e);
  });
  sip.value.on('registrationFailed', e => {
    console.log('registrationFailed', e);
  });
  sip.value.on('registrationExpiring', e => {
    console.log('registrationExpiring', e);
  });

  sip.value.on('ringing', e => {
    console.log('响铃中...', e);
    state.isRinging = true;
    if (e.originator === 'remote') {
      const isVideo = e.callType === 'video';
      ElMessageBox.alert(`来${isVideo ? '视频' : ''}电话了`, '提示', {
        callback(v, x) {
          if (v === 'confirm') {
            sip.value.answerCall();
          } else {
            sip.value.hangup();
          }
        },
      });
    }
  });
  sip.value.on('answer', e => {
    console.log('接听', e);
    state.isRinging = false;
    state.isCalling = true;
  });
  sip.value.on('hangup', e => {
    console.log('挂断');
    state.isRinging = false;
    state.isCalling = false;
  });
  sip.value.on('endDesktopSharing', e => {
    state.isShareDesk = false;
  });

  // sip.value.on('progress', e => {
  //   if (sip.value.originator === 'remote') {
  //     const isVideo = e.type === 'video';
  //     ElMessageBox.alert(`来${isVideo ? '视频' : ''}电话了`, '提示', {
  //       callback() {
  //         sip.value.answerCall();
  //       },
  //     });
  //   }
  // });
});
</script>
<style scoped lans="scss">
.test-sip {
  /* max-width: 800px; */
  margin: 0 auto;
  padding: 20px;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  color: #333;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.step {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.step h2 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
  color: #409eff;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.step-box {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
  /* 视频样式 */
  video {
    width: 320px;
    height: 240px;
    background-color: #000;
    border-radius: 4px;
    margin-right: 10px;
    margin-bottom: 10px;
    object-fit: cover;
    border: 1px solid #dcdfe6;
  }
}

.input-box {
  flex: 1;
  min-width: 200px;
}

.step-button {
  margin-right: 8px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .test-sip {
    padding: 15px;
  }

  .step-box {
    flex-direction: column;
    align-items: stretch;
  }

  .input-box {
    width: 100%;
    margin-bottom: 10px;
  }

  #meVideo,
  #remoteVideo {
    width: 100%;
    height: auto;
  }
}
</style>
